<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <div v-if="error">{{ error }}</div>
    <!-- <p>
      {{ form.rules[prop] }}
    </p> -->
  </div>
</template>

<script>
import Schema from "async-validate";
export default {
  inject: ["form"],
  name: "FormItem",
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: String, // 校验的字段名
  },
  data() {
    return {
      error: "",
    };
  },
  mounted() {
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    validate() {
      // 获取校验规则
      const rules = this.form.rules[this.prop];

      const value = this.form.model[this.prop];

      // 获取校验器，key是校验字段名，值是校验规则
      const validator = new Schema({
        [this.prop]: rules,
      });
      // 执行校验，参数1是校验目标

      return new Promise((resolve, reject) => {
        validator.validate(
          {
            [this.prop]: value,
          },
          (errors) => {
            if (errors) {
              // 校验失败
              this.error = errors[0].message;
              reject();
            } else {
              // 校验成功
              this.error = "";
              resolve();
            }
          }
        );
      });
    },
  },
};
</script>

<style>
</style>